<?php
/**
+-----------------------------------------------------------------------------------------------
* GouGuOPEN [ 左手研发，右手开源，未来可期！]
+-----------------------------------------------------------------------------------------------
* @Copyright (c) 2021~2024 http://www.gouguoa.com All rights reserved.
+-----------------------------------------------------------------------------------------------
* @Licensed 勾股OA，开源且可免费使用，但并不是自由软件，未经授权许可不能去除勾股OA的相关版权信息
+-----------------------------------------------------------------------------------------------
* @Author 勾股工作室 <hdm58@qq.com>
+-----------------------------------------------------------------------------------------------
*/

declare (strict_types = 1);

namespace app\customer\controller;

use app\base\BaseController;
use app\customer\model\CustomerTrace;
use app\customer\validate\TraceValidate;
use think\exception\ValidateException;
use think\facade\Db;
use think\response\Json;

class Trace extends BaseController
{
    protected $model;
    
    public function __construct()
    {
        parent::__construct();
        $this->model = new CustomerTrace();
    }

    /**
     * 跟进记录列表 - GET /customer/trace/index
     */
    public function index(): Json
    {
        $param = get_params();
        $uid = $this->uid;
        
        $where = [];
        $where[] = ['delete_time', '=', 0];
        
        // 关键词搜索
        if (!empty($param['keywords'])) {
            $where[] = ['content|contact_name', 'like', '%' . $param['keywords'] . '%'];
        }
        
        // 客户筛选
        if (!empty($param['customer_id'])) {
            $where[] = ['customer_id', '=', $param['customer_id']];
        }
        
        // 机会线索筛选
        if (!empty($param['chance_id'])) {
            $where[] = ['chance_id', '=', $param['chance_id']];
        }
        
        // 跟进类型筛选
        if (!empty($param['trace_type'])) {
            $where[] = ['trace_type', '=', $param['trace_type']];
        }
        
        // 时间筛选
        if (!empty($param['start_time']) && !empty($param['end_time'])) {
            $where[] = ['trace_time', 'between', [strtotime($param['start_time']), strtotime($param['end_time']) + 86399]];
        }
        
        // 数据权限控制
        $auth = isAuth($uid, 'customer_trace', 'conf_1');
        if ($auth == 0 || ($auth == 1 && !empty($param['uid']))) {
            $map = [];
            $mapOr = [];
            $map[] = ['delete_time', '=', 0];
            $map[] = ['discard_time', '=', 0];
            
            if (!empty($param['uid'])) {
                $map[] = ['belong_uid', '=', $param['uid']];
            } else {
                $mapOr[] = ['belong_uid', '=', $uid];
                $mapOr[] = ['', 'exp', Db::raw("FIND_IN_SET('{$uid}',share_ids)")];
                $mapOr[] = ['belong_did', 'in', get_leader_departments($uid)];
            }
            
            $cids = Db::name('Customer')
                ->where($map)
                ->where(function ($query) use($mapOr) {
                    if (!empty($mapOr)) {
                        $query->whereOr($mapOr);
                    }
                })
                ->column('id');
            $where[] = ['customer_id', 'in', $cids];
        }
        
        $list = $this->model->datalist($param, $where);
        return to_assign(0, '获取成功', $list);
    }

    /**
     * 查看跟进记录详情 - GET /customer/trace/show
     */
    public function show(): Json
    {
        $param = get_params();
        $id = $param['id'] ?? 0;
        
        if (empty($id)) {
            return to_assign(1, '参数错误');
        }
        
        $detail = $this->model->getById($id);
        if (empty($detail)) {
            return to_assign(1, '数据不存在');
        }
        
        return to_assign(0, '获取成功', $detail);
    }

    /**
     * 新增跟进记录 - POST /customer/trace/store
     */
    public function store(): Json
    {
        $param = get_params();
        
        try {
            validate(TraceValidate::class)->scene('add')->check($param);
        } catch (ValidateException $e) {
            return to_assign(1, $e->getError());
        }
        
        // 处理跟进时间
        if (!empty($param['trace_time'])) {
            $param['trace_time'] = strtotime($param['trace_time']);
        } else {
            $param['trace_time'] = time();
        }
        
        // 处理下次跟进时间
        if (!empty($param['next_time'])) {
            $param['next_time'] = strtotime($param['next_time']);
        }
        
        $param['admin_id'] = $this->uid;
        $param['create_time'] = time();
        
        $result = $this->model->add($param);
        if ($result) {
            // 更新客户最后跟进时间
            Db::name('Customer')
                ->where('id', $param['customer_id'])
                ->update(['last_trace_time' => $param['trace_time']]);
                
            return to_assign(0, '添加成功');
        } else {
            return to_assign(1, '添加失败');
        }
    }

    /**
     * 更新跟进记录 - PUT /customer/trace/update
     */
    public function update(): Json
    {
        $param = get_params();
        
        if (empty($param['id'])) {
            return to_assign(1, '参数错误');
        }
        
        try {
            validate(TraceValidate::class)->scene('edit')->check($param);
        } catch (ValidateException $e) {
            return to_assign(1, $e->getError());
        }
        
        // 处理跟进时间
        if (!empty($param['trace_time'])) {
            $param['trace_time'] = strtotime($param['trace_time']);
        }
        
        // 处理下次跟进时间
        if (!empty($param['next_time'])) {
            $param['next_time'] = strtotime($param['next_time']);
        }
        
        $param['update_time'] = time();
        
        $result = $this->model->edit($param);
        if ($result) {
            return to_assign(0, '更新成功');
        } else {
            return to_assign(1, '更新失败');
        }
    }

    /**
     * 删除跟进记录 - DELETE /customer/trace/destroy
     */
    public function destroy(): Json
    {
        $param = get_params();
        $id = $param['id'] ?? 0;
        
        if (empty($id)) {
            return to_assign(1, '参数错误');
        }
        
        $result = $this->model->delById($id);
        if ($result) {
            return to_assign(0, '删除成功');
        } else {
            return to_assign(1, '删除失败');
        }
    }

    /**
     * 跟进统计 - GET /customer/trace/statistics
     */
    public function statistics(): Json
    {
        $param = get_params();
        $uid = $this->uid;
        
        $where = [];
        $where[] = ['delete_time', '=', 0];
        
        // 时间范围
        $start_time = !empty($param['start_time']) ? strtotime($param['start_time']) : strtotime(date('Y-m-01'));
        $end_time = !empty($param['end_time']) ? strtotime($param['end_time']) + 86399 : time();
        $where[] = ['trace_time', 'between', [$start_time, $end_time]];
        
        // 数据权限控制
        if (!empty($param['uid'])) {
            $where[] = ['admin_id', '=', $param['uid']];
        } else {
            $where[] = ['admin_id', '=', $uid];
        }
        
        // 按跟进类型统计
        $type_stats = Db::name('CustomerTrace')
            ->where($where)
            ->group('trace_type')
            ->field('trace_type, count(*) as count')
            ->select()
            ->toArray();
            
        // 按日期统计
        $date_stats = Db::name('CustomerTrace')
            ->where($where)
            ->group('FROM_UNIXTIME(trace_time, "%Y-%m-%d")')
            ->field('FROM_UNIXTIME(trace_time, "%Y-%m-%d") as date, count(*) as count')
            ->order('date')
            ->select()
            ->toArray();
            
        // 总数统计
        $total = Db::name('CustomerTrace')->where($where)->count();
        
        $result = [
            'total' => $total,
            'type_stats' => $type_stats,
            'date_stats' => $date_stats
        ];
        
        return to_assign(0, '获取成功', $result);
    }

    /**
     * 获取跟进记录选项 - GET /customer/trace/options
     */
    public function options(): Json
    {
        $param = get_params();
        $customer_id = $param['customer_id'] ?? 0;
        
        $where = [];
        $where[] = ['delete_time', '=', 0];
        
        if ($customer_id > 0) {
            $where[] = ['customer_id', '=', $customer_id];
        }
        
        $list = Db::name('CustomerTrace')
            ->where($where)
            ->field('id,content,customer_id,trace_time,trace_type')
            ->order('trace_time desc')
            ->select()
            ->toArray();
            
        return to_assign(0, '获取成功', $list);
    }
}